/*
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.module.xmlconfig;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.StringTokenizer;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import tal.drivechain.module.properties.PropertyParser;
import tal.drivechain.module.properties.PropertyParserFactory;

/**
 *
 * @author Main
 */
public class PropertyInfo {

    private String name;
    private String description;
    private PropertyParser parser;
    private HashMap<String,String> attributes;


    public static PropertyInfo createPropertyInfo(String name, String description, PropertyParser parser, HashMap<String,String> attributes) {
        return new PropertyInfo(name, description, parser, attributes);
    }

    public static PropertyInfo createPropertyInfo(String name, String description, PropertyParser parser) {
        return new PropertyInfo(name, description, parser, new HashMap<String,String>());
    }

    PropertyInfo(String name, String description, PropertyParser parser, HashMap<String,String> attributes) {
        this.name = name.replaceAll("\\s+", " ").trim();
        this.description = description.replaceAll("\\s+", " ").trim();
        this.parser = parser;
        this.attributes = attributes;
    }

    PropertyInfo(Node propertyNode) throws IllegalArgumentException {
        attributes = new HashMap<String,String>();

        name = propertyNode.getAttributes().getNamedItem("name").getNodeValue().replaceAll("\\s+", " ").trim();
        NodeList children = propertyNode.getChildNodes();
        for (int i=0; i<children.getLength(); i++) {
            Node currentChild = children.item(i);
            if (currentChild.getNodeName().equals("description")) {
                description = currentChild.getTextContent().replaceAll("\\s+", " ").trim();
            } else if (currentChild.getNodeName().equals("attribute")) {
                String key = currentChild.getAttributes().getNamedItem("name").getNodeValue().trim();
                String value = currentChild.getAttributes().getNamedItem("value").getNodeValue().trim();
                attributes.put(key, value);
            } else if (!currentChild.getNodeName().equals("#text")) { // treat anything else as a property parser
                String parserName = currentChild.getNodeName().trim();
                HashMap<String,String> parserAttributes = getParserAttributes(currentChild);
                NodeList childElements = currentChild.getChildNodes();
                parserAttributes.put("property-name", name);
                try {
                    parser = PropertyParserFactory.createParser(parserName, parserAttributes, childElements);
                } catch (IllegalArgumentException ex) {
                    throw new IllegalArgumentException("at property " + this.getName() + ", " + ex.getMessage());
                }
            }
        }
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public PropertyParser getParser() {
        return parser;
    }

    public HashMap<String, String> getAttributes() {
        return attributes;
    }
    
    public boolean isOrdered() {
        return attributes.containsKey("ordered");
    }
    
    public int getOrderIndex() throws IllegalArgumentException {
        if (isOrdered()) {
            String index = attributes.get("ordered");
            try {
                return Integer.parseInt(index)-1;
            } catch (NumberFormatException ne) {
                throw new IllegalArgumentException("Invalid 'ordered' attribute value: " + index);
            }
        } else throw new IllegalArgumentException("Property " + getName() + " is not an ordered property.");
    }
    
    public boolean isOptional() {
        return attributes.containsKey("optional");
    }
    
    public String getDefaultValueString() {
        if (isOptional()) {
            return attributes.get("optional");
        } else return null;
    }

     public Object getDefaultValue() {
        if (isOptional()) {
            String opt = attributes.get("optional");
            if (opt.equals("?")) return null;
            else if (isRepeatable() && opt.equals("empty")) {
                return new ArrayList<Object>();
            } else {
                Object val = this.getParser().parseProperty(opt);
                if (isRepeatable()) {
                    List ret = new ArrayList();
                    ret.add(val);
                    return ret;
                } else return val;
            }
        } else return null;
    }
    
    public boolean isRepeatable() {
        return attributes.containsKey("repeatable");
    }

    private HashMap<String, String> getParserAttributes(Node currentChild) {
        HashMap<String,String> parserAttributes = new HashMap<String,String>();
        NamedNodeMap nodeAttributes = currentChild.getAttributes();
        if (nodeAttributes!=null) {
            for (int i=0; i<nodeAttributes.getLength(); i++) {
                parserAttributes.put(nodeAttributes.item(i).getNodeName().trim(),
                        nodeAttributes.item(i).getNodeValue().trim());
            }
        }
        return parserAttributes;
    }
    
    @Override
    public String toString() { return getName(); }

    public String getNameForMethod() {
        return propNameToMethodName(getName());
    }

    public static String propNameToMethodName(String propName) {
        StringTokenizer t = new StringTokenizer(propName, ":-.");
        String methodName = "";
        while (t.hasMoreTokens()) {
            String part = t.nextToken();
            methodName += part.substring(0,1).toUpperCase() + part.substring(1);
        }

        return methodName;
    }

}
